package com.example.securtydemo.config;

import com.example.securtydemo.permission.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

@Service
public class AuthService {
    @Autowired
    private PermissionService permissionService;

    public boolean canAcess(HttpServletRequest request, Authentication authentication) {
        boolean b = false;

        String url = request.getRequestURI();

        /**
         * 1、未登录的情况下，需要坐一个判断或者是拦截。
         */Object principal = authentication.getPrincipal();
        if (principal == null || "anonymousUser".equals(principal)) {
            return b;
        }

        /**
         * 2、匿名的角色ROLE_ANONYMOUS
         */
        if (authentication instanceof AnonymousAuthenticationToken) {
            // 匿名角色
            // check
            // return
        }

        /**
         * 3、通过requst对象url,获取到权限信息
         */
        Map<String, Collection<ConfigAttribute>> map = permissionService.getPermissionMap();
        Collection<ConfigAttribute> configAttributes = null;
        for (Iterator<String> it = map.keySet().iterator(); it.hasNext(); ) {
            String curUrl = it.next();
            AntPathRequestMatcher matcher = new AntPathRequestMatcher(curUrl);
            if (matcher.matches((request))) {
                configAttributes = map.get(curUrl);
                break;
            }
        }

        if (configAttributes == null || configAttributes.size() == 0) {
            return b;
        }

        /**
         * 4、将获取到的权限信息和当前的登陆账号的权限信息进行对比
         */
        for (Iterator<ConfigAttribute> it = configAttributes.iterator(); it.hasNext(); ) {
            ConfigAttribute cfa = it.next();
            String role = cfa.getAttribute();
            for (GrantedAuthority authority : authentication.getAuthorities()) {
                if (role.equals(authority.getAuthority())) {
                    b = true;
                    break;
                }
            }
        }

        return b;
    }
}
